<template>
  <div class="api-node-config">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="节点名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入节点名称" />
      </el-form-item>
      
      <el-form-item label="选择接口" prop="interfaceId">
        <el-select 
          v-model="form.interfaceId" 
          placeholder="请选择API接口"
          style="width: 100%"
          filterable
          @change="onInterfaceChange"
        >
          <el-option
            v-for="iface in interfaces"
            :key="iface.id"
            :label="`${iface.method} ${iface.name}`"
            :value="iface.id"
          >
            <div class="interface-option">
              <el-tag :type="getMethodType(iface.method)" size="small">
                {{ iface.method }}
              </el-tag>
              <span class="interface-name">{{ iface.name }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 接口信息展示 -->
      <div v-if="selectedInterface" class="interface-info">
        <el-divider content-position="left">接口信息</el-divider>
        <div class="interface-detail">
          <p><strong>URL:</strong> {{ selectedInterface.url }}</p>
          <p><strong>描述:</strong> {{ selectedInterface.description || '无' }}</p>
        </div>
      </div>

      <!-- 参数覆盖 -->
      <el-form-item label="参数覆盖">
        <div class="parameter-overrides">
          <div class="section-header">
            <span>覆盖接口默认参数值</span>
            <el-button size="small" type="primary" @click="addParameterOverride">
              <el-icon><Plus /></el-icon>
              添加参数
            </el-button>
          </div>
          
          <div v-if="parameterOverrides.length === 0" class="empty-state">
            <el-empty :image-size="60" description="暂无参数覆盖" />
          </div>
          
          <div v-else class="parameter-list">
            <div 
              v-for="(override, index) in parameterOverrides" 
              :key="index"
              class="parameter-item"
            >
              <el-input
                v-model="override.name"
                placeholder="参数名"
                style="width: 30%"
              />
              <el-input
                v-model="override.value"
                placeholder="参数值 (支持变量: {variableName})"
                style="width: 60%; margin-left: 10px"
              >
                <template #suffix>
                  <el-tooltip content="变量格式: {变量名}&#10;例如: {userId}, {token}" placement="top">
                    <el-icon style="cursor: help"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </template>
              </el-input>
              <el-button 
                type="danger" 
                size="small" 
                @click="removeParameterOverride(index)"
                style="margin-left: 10px"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </el-form-item>

      <!-- 变量提取 -->
      <el-form-item label="变量提取">
        <div class="variable-extractions">
          <div class="section-header">
            <span>从响应中提取变量</span>
            <el-button size="small" type="success" @click="addVariableExtraction">
              <el-icon><Plus /></el-icon>
              添加提取
            </el-button>
          </div>
          
          <div v-if="variableExtractions.length === 0" class="empty-state">
            <el-empty :image-size="60" description="暂无变量提取" />
          </div>
          
          <div v-else class="variable-list">
            <div 
              v-for="(extraction, index) in variableExtractions" 
              :key="index"
              class="variable-item"
            >
              <el-input
                v-model="extraction.name"
                placeholder="变量名"
                style="width: 25%"
              />
              <el-select
                v-model="extraction.type"
                placeholder="提取方式"
                style="width: 25%; margin-left: 10px"
              >
                <el-option label="JSONPath" value="jsonpath" />
                <el-option label="正则表达式" value="regex" />
                <el-option label="响应头" value="header" />
              </el-select>
              <el-input
                v-model="extraction.expression"
                placeholder="提取表达式"
                style="width: 40%; margin-left: 10px"
              >
                <template #suffix>
                  <el-tooltip :content="getExtractionTooltip(extraction.type)" placement="top">
                    <el-icon style="cursor: help"><QuestionFilled /></el-icon>
                  </el-tooltip>
                </template>
              </el-input>
              <el-button 
                type="danger" 
                size="small" 
                @click="removeVariableExtraction(index)"
                style="margin-left: 10px"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </el-form-item>

      <!-- 执行配置 -->
      <el-form-item label="执行配置">
        <div class="execution-config">
          <el-checkbox v-model="form.continueOnFailure">失败时继续执行</el-checkbox>
          <el-checkbox v-model="form.isEnabled">启用此节点</el-checkbox>
        </div>
      </el-form-item>
    </el-form>

    <div class="dialog-footer">
      <div class="footer-left">
        <el-button type="danger" @click="handleDelete">
          <el-icon><Delete /></el-icon>
          删除节点
        </el-button>
      </div>
      <div class="footer-right">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { Plus, Delete, QuestionFilled } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'

const props = defineProps({
  nodeData: {
    type: Object,
    required: true
  },
  interfaces: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['save', 'cancel', 'delete'])

const formRef = ref()

// 表单数据
const form = reactive({
  name: props.nodeData.data?.label || '接口调用',
  interfaceId: props.nodeData.data?.config?.interfaceId || null,
  continueOnFailure: props.nodeData.data?.config?.continueOnFailure || false,
  isEnabled: props.nodeData.data?.config?.isEnabled !== false
})

// 参数覆盖列表
const parameterOverrides = ref([])
const variableExtractions = ref([])

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入节点名称', trigger: 'blur' }
  ],
  interfaceId: [
    { required: true, message: '请选择API接口', trigger: 'change' }
  ]
}

// 选中的接口信息
const selectedInterface = computed(() => {
  if (!form.interfaceId) return null
  return props.interfaces.find(iface => iface.id === form.interfaceId)
})

// 初始化数据
const initializeData = () => {
  const config = props.nodeData.data?.config || {}
  
  // 初始化参数覆盖
  if (config.parameterOverrides) {
    parameterOverrides.value = Object.entries(config.parameterOverrides).map(([name, value]) => ({
      name,
      value
    }))
  }
  
  // 初始化变量提取
  if (config.variableExtractions) {
    variableExtractions.value = Object.entries(config.variableExtractions).map(([name, extraction]) => ({
      name,
      type: extraction.type || 'jsonpath',
      expression: extraction.expression || ''
    }))
  }
}

// 获取HTTP方法对应的标签类型
const getMethodType = (method) => {
  const typeMap = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  }
  return typeMap[method] || 'info'
}

// 接口变化处理
const onInterfaceChange = () => {
  // 可以在这里根据选中的接口自动填充一些默认参数
}

// 添加参数覆盖
const addParameterOverride = () => {
  parameterOverrides.value.push({
    name: '',
    value: ''
  })
}

// 移除参数覆盖
const removeParameterOverride = (index) => {
  parameterOverrides.value.splice(index, 1)
}

// 添加变量提取
const addVariableExtraction = () => {
  variableExtractions.value.push({
    name: '',
    type: 'jsonpath',
    expression: ''
  })
}

// 移除变量提取
const removeVariableExtraction = (index) => {
  variableExtractions.value.splice(index, 1)
}

// 获取提取方式的提示信息
const getExtractionTooltip = (type) => {
  const tooltips = {
    jsonpath: 'JSONPath表达式\n例如: $.data.id, $.user.name',
    regex: '正则表达式\n例如: "token":"([^"]+)"',
    header: '响应头名称\n例如: Authorization, Set-Cookie'
  }
  return tooltips[type] || ''
}

// 处理保存
const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    // 构建配置数据
    const config = {
      interfaceId: form.interfaceId,
      continueOnFailure: form.continueOnFailure,
      isEnabled: form.isEnabled,
      parameterOverrides: {},
      variableExtractions: {}
    }
    
    // 处理参数覆盖
    parameterOverrides.value.forEach(override => {
      if (override.name && override.value) {
        config.parameterOverrides[override.name] = override.value
      }
    })
    
    // 处理变量提取
    variableExtractions.value.forEach(extraction => {
      if (extraction.name && extraction.expression) {
        config.variableExtractions[extraction.name] = {
          type: extraction.type,
          expression: extraction.expression
        }
      }
    })
    
    emit('save', {
      name: form.name,
      ...config
    })
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 处理取消
const handleCancel = () => {
  emit('cancel')
}

// 处理删除
const handleDelete = () => {
  ElMessageBox.confirm(
    '确定要删除这个节点吗？此操作不可撤销。',
    '删除节点',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    emit('delete', props.nodeData)
  }).catch(() => {
    // 用户取消删除
  })
}

// 初始化
initializeData()
</script>

<style scoped>
.api-node-config {
  max-height: 70vh;
  overflow-y: auto;
  padding: 16px;
  font-size: 13px;
}

/* 表单标签样式优化 */
.api-node-config :deep(.el-form-item__label) {
  font-size: 13px;
  font-weight: 600;
  color: #303133;
}

/* 输入框字体大小 */
.api-node-config :deep(.el-input__inner),
.api-node-config :deep(.el-select .el-input__inner),
.api-node-config :deep(.el-textarea__inner) {
  font-size: 13px;
}

.interface-option {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
}

.interface-name {
  flex: 1;
}

.interface-info {
  margin: 12px 0;
}

.interface-detail {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 6px;
  font-size: 12px;
}

.interface-detail p {
  margin: 3px 0;
}

.interface-detail p strong {
  font-weight: 600;
  color: #409eff;
}

.parameter-overrides,
.variable-extractions {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  background: #fafbfc;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-weight: 600;
  font-size: 13px;
  color: #303133;
}

.empty-state {
  text-align: center;
  padding: 16px;
}

.empty-state :deep(.el-empty__description) {
  font-size: 12px;
}

.parameter-list,
.variable-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.parameter-item,
.variable-item {
  display: flex;
  align-items: center;
  padding: 6px 8px;
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.parameter-item .el-input,
.variable-item .el-input {
  font-size: 12px;
}

.parameter-item .el-button,
.variable-item .el-button {
  min-width: 32px;
  height: 28px;
}

.execution-config {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.execution-config .el-form-item {
  margin-bottom: 12px;
}

.dialog-footer {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
}

.footer-left {
  display: flex;
}

.footer-right {
  display: flex;
}

.dialog-footer .el-button {
  margin-left: 8px;
  font-size: 13px;
}

.footer-left .el-button {
  margin-left: 0;
  margin-right: 8px;
}

/* 分割线样式 */
.api-node-config :deep(.el-divider__text) {
  font-size: 12px;
  font-weight: 600;
  color: #606266;
}

/* 工具提示样式 */
.api-node-config :deep(.el-tooltip__trigger) {
  font-size: 12px;
}
</style>